package q203_removeElements;

import CommonClass.Common.ListNode;

public class Solution_1 {
    /*
    稍显繁琐的解法
    首先建立一个哑节点，其next为head
    1 然后对于head 如果head == val
    则不断循环直至head != val
    2 接下来用一个prev来记录head的前一个节点
    如果head == val 则将prev的next接到head的后面
    否则prev和head同时后移
    最后返回dummy.next
     */
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return null;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;

        while (head != null && head.val == val) {
            dummy.next = head.next;
            head = head.next;
        }

        ListNode prev = dummy;
        while (head != null) {
            if (head.val == val) {
                prev.next = head.next;
            }else {
                prev = head;
            }
            head = head.next;
        }
        return dummy.next;
    }
}
